import { useCallback, useEffect, useRef, useState } from 'react'
import { useLocalStorage } from '../use-locastorage'
import color from 'color'
import s from './LinkerBoard.module.less'
import { stoerKeys } from '@renderer/store-keys'

type LinkerItem = {
  id: string
  url: string
  label: string
  color: string
}

function genId() {
  return Math.random().toString(16).slice(2)
}

export function LinkerBoard() {
  const [url, setUrl] = useState('')
  const [label, setLabel] = useState('')
  const [id, setId] = useState(genId)
  const [linker, setLinker] = useLocalStorage<LinkerItem[]>(stoerKeys.LINKER_IMTES, [])
  const [editing, setEditing] = useState(false)
  const [filter, setFilter] = useState('')

  useEffect(() => {
    if (filter) {
      if (filter === '@sort') {
        setLinker((linker) =>
          [...linker].sort((a, b) => {
            return a.label.localeCompare(b.label)
          })
        )
        setFilter('')
      }
    }
  }, [filter, setLinker])

  const urlInp = useRef<HTMLInputElement>(null)
  const labelInp = useRef<HTMLInputElement>(null)

  const onClear = useCallback(() => {
    setId('')
    setUrl('')
    setLabel('')
    setEditing(false)
  }, [])

  const onConfirm = (savingId = genId()) => {
    if (!url || !label) return

    setLinker((l) => {
      if (savingId) {
        const found = l.find((v) => v.id === savingId)
        if (found) {
          found.url = url
          found.label = label
          return [...l]
        }
      }

      // default create new record
      return [
        {
          id: savingId,
          url,
          label,
          color: color.hsl(360 * Math.random(), 50, 50).toString()
        },
        ...l
      ]
    })
    onClear()

    urlInp.current?.focus()
  }

  return (
    <div className={s.linkerBoard}>
      <div className={s.inputLine}>
        <input
          ref={urlInp}
          placeholder="地址, eg: http://www.mindlinker.com"
          value={url}
          onChange={(ev) => setUrl(ev.target.value)}
          onKeyDown={(ev) => {
            if (ev.key === 'Enter') {
              if (labelInp.current && !labelInp.current.value) {
                labelInp.current.focus()
              } else {
                onConfirm()
              }
            }
          }}
        ></input>
        <input
          ref={labelInp}
          value={label}
          placeholder="名称, eg: 迈聆"
          onChange={(ev) => setLabel(ev.target.value)}
          onKeyDown={(ev) => {
            if (ev.key === 'Enter') {
              if (urlInp.current && !urlInp.current.value) {
                urlInp.current.focus()
              } else {
                onConfirm()
              }
            }
          }}
        ></input>
      </div>
      <div className={s.filterLine}>
        <button
          onClick={() => {
            onConfirm(genId())
          }}
        >
          新记录
        </button>
        {editing && (
          <button
            className="second"
            onClick={() => {
              onConfirm(id)
              onClear()
              urlInp.current?.focus()
            }}
          >
            保存修改
          </button>
        )}
        {editing && (
          <button
            className="second"
            onClick={() => {
              onClear()
              urlInp.current?.focus()
            }}
          >
            取消修改
          </button>
        )}
        {editing && (
          <button
            className="delete"
            onClick={() => {
              setLinker((list) => list.filter((v) => v.id !== id))
              onClear()
            }}
          >
            删除
          </button>
        )}
        <input
          className={s.filterLineInput}
          placeholder="筛选记录 (鼠标右键清空过滤条件)"
          value={filter}
          onChange={(ev) => setFilter(ev.target.value)}
          onContextMenu={() => {
            setFilter('')
          }}
        ></input>
      </div>
      <div className={s.linkerItemsList}>
        {...linker
          .filter((l) => {
            return l.label.includes(filter) || l.url.includes(filter)
          })
          .map((l) => {
            return (
              <div
                className={s.linkerItem + (l.id === id ? ' ' + s.focused : '')}
                key={l.id}
                onClick={() => {
                  setId(l.id)
                  setUrl(l.url)
                  setLabel(l.label)
                  setEditing(true)
                }}
              >
                <a
                  onClick={(ev) => {
                    ev.preventDefault()
                    ev.stopPropagation()
                    window.api.open(l.url).catch((err) => {
                      alert(err)
                    })
                  }}
                  style={{ color: l.color }}
                >
                  {l.label}
                </a>
                <span className={s.linkerItemUrlText}>{l.url}</span>
              </div>
            )
          })}
      </div>
    </div>
  )
}
